package io.modifier.basic.compose.paging

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState

class BaseDataPagingSource<T : Any>(
    private val defStartPage: Int = 1,
    private val loadData: suspend (pageNo: Int, pageSize: Int) -> List<T>,
) : PagingSource<Int, T>() {
    override fun getRefreshKey(state: PagingState<Int, T>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, T> {
        val pageNo = params.key ?: defStartPage
        val pageSize = params.loadSize
        return try {
            val response = loadData(pageNo, pageSize)
            val previousPage = if (pageNo > defStartPage) pageNo - 1 else null
            val nextPage = if (response.size >= pageSize) pageNo + 1 else null
//            LogX.d("pageNo:$pageNo,pageSize:$pageSize, response:${response.size}, previousPage:$previousPage, nextPage:$nextPage")
            LoadResult.Page(
                data = response,
                prevKey = previousPage,
                nextKey = nextPage,
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}


// 使用
//  fun getSearchSongResult(keywords:String) = commPagerCreator { offset, limit ->
//        val response = service.getSearchSongResult(keywords = keywords,offset = offset*limit,limit = limit)
//        response.result.songs
//    }.flow.cachedIn(viewModelScope)
//
//  val songs = viewModel.getSearchSongResult(value.keyword).collectAsLazyPagingItems()

fun <T : Any> commPagerCreator(
    pageSize: Int,
    defStartPage: Int = 1,
    prefetchDistance: Int = 1,
    enablePlaceholders: Boolean = false,
    loadData: suspend (pageNo: Int, pageSize: Int) -> List<T>,
): Pager<Int, T> = Pager(
    config = PagingConfig(
        pageSize = pageSize,
        initialLoadSize = pageSize,
        enablePlaceholders = enablePlaceholders,
        prefetchDistance = prefetchDistance,
    ),
    pagingSourceFactory = { BaseDataPagingSource(defStartPage = defStartPage, loadData = loadData) },
)

